//
//  MBActivityDetailsController.m
//  LiveBroadcast
//
//  Created by 肖剑 on 2019/3/27.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBActivityDetailsController.h"
#import "MBActivityCollectionCell.h"
#import "MBAWardDetailController.h"
#import "MBFinshJoinView.h"
#import "MBShortVideoPlayController.h"
#import "MBShortVideoRecordConfig.h"
#import "MBShortVideoController.h"
@interface MBActivityDetailsController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIScrollView *_scrollView;
    UIView *view;
    UICollectionView *_collectionView;
    NSArray *labels;
    UILabel *activityLbl;
    UILabel *activityDetail;
    
    UIImageView *topView;
    MBFinshJoinView *joinView;
    UIView *joinBgView;
    
    MBButton *joinBtn;
}
@end

@implementation MBActivityDetailsController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化控件
    [self initView];
    labels = [NSArray array];
    self.title = @"活动详情";
//    [MBHttpRequset requestWithUrl:kTradeid_activity_getActivityLabel setParams:@{} isShowProgressView:NO success:^(id  _Nonnull AJson) {
//        self->labels = AJson[@"labelAllList"];
//        self->_collectionView.height = ((IPHONE_SCREEN_WIDTH - 20)/2) * (self->labels.count/2 + self->labels.count%2) + ((self->labels.count/2) + self->labels.count%2 - 1)* 20;
//        self->_scrollView.contentSize = CGSizeMake(0, 400 + self->_collectionView.height);
//        [self->_collectionView reloadData];
//    } failure:^(id  _Nonnull AJson) {
//
//    }];
    
    if ([MBUserModel sharedMBUserModel].userInfo.userId != nil) {
        NSString *activityId = [NSString stringWithFormat:@"%@",self.acitivityData[@"activityInfo"][@"id"]];
        NSDictionary *dict = @{
                               @"pageNo":@"1",
                               @"activityId":activityId,
                               @"userId":[MBUserModel sharedMBUserModel].userInfo.userId
                               };
        [MBHttpRequset requestWithUrl:kTradeid_activity_getActivityJoinList setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
            self->labels = AJson[@"activityJoinList"];
            if (self->labels.count != 0) {
                self->_collectionView.height = ((IPHONE_SCREEN_WIDTH - 15)/3) * (self->labels.count/3 + self->labels.count%3)*1.5 + ((self->labels.count/3) + self->labels.count%3 - 1)* 15;
                self->_scrollView.contentSize = CGSizeMake(0, self->_collectionView.bottom + 10);
                [self->_collectionView reloadData];
            }
        } failure:^(id  _Nonnull AJson) {
            
        }];
    }else{
        // 请登录
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appDelegate needLoginVC:self];
    }
}

- (void)setAcitivityData:(NSDictionary *)acitivityData
{
    _acitivityData = acitivityData;
    
    
    
}

// 初始化控件
- (void)initView
{
    _scrollView = [[MBBaseScrollView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_SCREEN_WIDTH, IPHONE_SCREEN_HEIGHT)];
    _scrollView.backgroundColor = self.view.backgroundColor;
    _scrollView.delegate = self;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    self.view = _scrollView;
    // 用户顶部图
    topView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,375,180)];
    topView.contentMode = UIViewContentModeScaleAspectFill;
    topView.clipsToBounds = YES;
    topView.userInteractionEnabled=YES;
    //初始化一个手势
    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topViewClick)];
    //为图片添加手势
    [topView addGestureRecognizer:tapGesturRecognizer];
    [topView sd_setImageWithURL:[NSURL URLWithString:self.acitivityData[@"activityInfo"][@"activityUrl"]] placeholderImage:[UIImage imageNamed:@"bg.png"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        UIImage *image1=[image stretchableImageWithLeftCapWidth:image.size.width*0.001 topCapHeight:image.size.height*0.001];
        self->topView.image = image1;
    }];
    [_scrollView addSubview:topView];
    
    
    
    // centerView
    UIView *centerView = [[UIView alloc]initWithFrame:CGRectMake(0, topView.bottom, IPHONE_SCREEN_WIDTH, 225)];
    centerView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:centerView];
    
    activityLbl = [[UILabel alloc]init];
    activityLbl.frame = CGRectMake(20, 30, IPHONE_SCREEN_WIDTH - 40, 20);
    activityLbl.text = self.acitivityData[@"activityInfo"][@"activityTitle"];
    activityLbl.font = [UIFont systemFontOfSize:16.0f];
    [centerView addSubview:activityLbl];
    
    activityDetail = [[UILabel alloc]init];
    activityDetail.frame = CGRectMake(20, activityLbl.bottom + 10, IPHONE_SCREEN_WIDTH - 40, 90);
    activityDetail.text = self.acitivityData[@"activityInfo"][@"activityContent"];
    activityDetail.font = [UIFont systemFontOfSize:14.0f];
    activityDetail.numberOfLines = 0;
    activityLbl.textColor = kColorRGBA(51, 51, 51, 1);
    [centerView addSubview:activityDetail];
    
    MBButton *joinBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    joinBtn.frame = CGRectMake(20, activityDetail.bottom + 20, IPHONE_SCREEN_WIDTH - 40, 44);
    joinBtn.backgroundColor = [UIColor grayColor];
//    [joinBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [joinBtn setTitle:@"已结束" forState:UIControlStateNormal];
    [joinBtn addTarget:self action:@selector(joinActivity) forControlEvents:UIControlEventTouchUpInside];
    joinBtn.enabled = NO;
    joinBtn.layer.cornerRadius = 10;
    [centerView addSubview:joinBtn];
    
    if ([self.acitivityData[@"activityInfo"][@"activityState"] isEqualToString:@"1"]) {// 活动进行中
        joinBtn.enabled = YES;
        joinBtn.backgroundColor = [UIColor colorWithRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:1.0];
        [joinBtn setTitle:@"参与报名" forState:UIControlStateNormal];
    }
    
    UILabel *activity = [[UILabel alloc]init];
    activity.frame = CGRectMake(0, centerView.bottom + 20, IPHONE_SCREEN_WIDTH, 40);
    activity.text = @"   活动";
    activity.backgroundColor = [UIColor whiteColor];
    activity.font = [UIFont systemFontOfSize:16.0f];
    [_scrollView addSubview:activity];
    
    UIView *userV = [[UIView alloc]initWithFrame:CGRectMake(10, 180 - 20, IPHONE_SCREEN_WIDTH - 20, 40)];
    userV.backgroundColor = [UIColor whiteColor];
    userV.hidden = YES;
    [_scrollView addSubview:userV];
    
    // 头像
    UIButton *userBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    userBtn.frame = CGRectMake(20, 5, 30, 30);
    userBtn.layer.cornerRadius = 15;
    [userV addSubview:userBtn];
    
    UILabel *userLbl = [[UILabel alloc]init];
    userLbl.frame = CGRectMake(userBtn.right + 10, 10, 150, 20);
    userLbl.textColor = kColorRGBA(51, 51, 51, 1);
    userLbl.font = [UIFont systemFontOfSize:14.0f];
    [userV addSubview:userLbl];
    
    UILabel *lbl = [[UILabel alloc]init];
    lbl.frame = CGRectMake(userLbl.right, 15, 70, 10);
    lbl.textColor = [UIColor colorWithRed:240/255.0 green:161/255.0 blue:58/255.0 alpha:1.0];
    lbl.backgroundColor = [UIColor colorWithRed:255/255.0 green:246/255.0 blue:229/255.0 alpha:1.0];
    lbl.font = [UIFont systemFontOfSize:12.0f];
    lbl.text = @"奖品提供者";
    lbl.textAlignment = NSTextAlignmentCenter;
    [userV addSubview:lbl];
    
    NSDictionary *dict = self.acitivityData[@"userInfo"];
    if (dict.allKeys.count != 0) {
        [userBtn sd_setImageWithURL:[NSURL URLWithString:dict[@"headUrl"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"bg"]];
        userLbl.text = dict[@"nickname"];
        userV.hidden = NO;
    }
    
    // 作品
    UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, activity.bottom, IPHONE_SCREEN_WIDTH, 0) collectionViewLayout:fl];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = activity.backgroundColor;
    _collectionView.scrollEnabled = NO;
    [_scrollView addSubview: _collectionView];
    
    
    joinBgView = [[UIView alloc] init];
    joinBgView.frame = UIScreen.mainScreen.bounds;
    joinBgView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.5];
    joinBgView.hidden = YES;
    [_scrollView addSubview: joinBgView];
    
    NSArray *nibView =  [[NSBundle mainBundle] loadNibNamed:@"MBFinshJoinView"owner:self options:nil];
    joinView = [nibView objectAtIndex:0];
    joinView.frame = CGRectMake(20, 140,(IPHONE_SCREEN_WIDTH - 40), 360);
    [joinBgView addSubview:joinView];
    joinView.cancleBtn.miBtnBlock = ^(){
        self->joinBgView.hidden = YES;
    };
    
    // 提交活动
    joinView.commitBtn.miBtnBlock = ^(){
        MBShortVideoRecordConfig* videoConfig = [[MBShortVideoRecordConfig alloc]init];
        MBShortVideoController *vc = [[MBShortVideoController alloc]initWithConfigure:videoConfig];
        vc.MAX_RECORD_TIME = 11.0f;
        vc.entityType = MBShortVideoEntityTypeIdle;
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    
    //布局
    fl.minimumInteritemSpacing = 0;
    fl.minimumLineSpacing = 5;
    [_collectionView registerNib:[UINib nibWithNibName:@"MBActivityCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"MBActivityCollectionCell"];
}

- (void)topViewClick
{
    NSLog(@"头部点击事件");
}

- (void)joinActivity
{
    if ([MBUserModel sharedMBUserModel].userInfo.userId != nil) {
        NSDictionary *dict = @{
                               @"activityId":_acitivityData[@"activityInfo"][@"id"],
                               @"userId":[MBUserModel sharedMBUserModel].userInfo.userId
                               };
        __block MBFinshJoinView *jv = joinView;
        [MBHttpRequset requestWithUrl:kTradeid_activity_participateActivity setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
            NSDictionary *dict = AJson;
            /*
             fansResult = 2;
             joinFansCount = 5;
             joinNewCount = 6;
             joinPraiseCount = 7;
             joinVideoCount = 2;
             newResult = 2;
             praiseResult = 2;
             videoResult = 2;
             */
            
            
            self->joinBgView.hidden = NO;
            jv.videoLbl.text = [NSString stringWithFormat:@"还需再拍摄%@/%@个视频",dict[@"currentVideoCount"],dict[@"joinVideoCount"]];
            jv.fansLbl.text = [NSString stringWithFormat:@"还需%@/%@粉丝量",dict[@"currentFansCount"],dict[@"joinFansCount"]];
            jv.praiseLbl.text = [NSString stringWithFormat:@"还需%@/%@获赞量",dict[@"currentPraiseCount"],dict[@"joinPraiseCount"]];
            jv.nwLbl.text = [NSString stringWithFormat:@"还需拉新%@/%@人",dict[@"currentNewCount"],dict[@"joinNewCount"]];
            
            if ([dict[@"fansResult"] isEqualToString:@"1"]) {
                [jv.fansBtn setTitle:@"已完成" forState:UIControlStateNormal];
            }else{
                jv.fansBtn.miBtnBlock = ^(){
                    NSLog(@"fansBtn");
                };
            }
            
            if ([dict[@"newResult"] isEqualToString:@"1"]) {
                [jv.nwBtn setTitle:@"已完成" forState:UIControlStateNormal];
            }else{
                jv.nwBtn.miBtnBlock = ^(){
                    NSLog(@"nwBtn");
                };
            }
            
            if ([dict[@"praiseResult"] isEqualToString:@"1"]) {
                [jv.praiseBtn setTitle:@"已完成" forState:UIControlStateNormal];
            }else{
                jv.praiseBtn.miBtnBlock = ^(){
                    NSLog(@"praiseBtn");
                };
            }
            
            if ([dict[@"videoResult"] isEqualToString:@"1"]) {
                [jv.videoBtn setTitle:@"已完成" forState:UIControlStateNormal];
            }else{
                jv.videoBtn.miBtnBlock = ^(){
                    NSLog(@"videoBtn");
                };
            }
            
            if ([jv.fansBtn.currentTitle isEqualToString:@"已完成"] && [jv.nwBtn.currentTitle isEqualToString:@"已完成"] && [jv.praiseBtn.currentTitle isEqualToString:@"已完成"] && [jv.videoBtn.currentTitle isEqualToString:@"已完成"]) {
                jv.commitBtn.hidden = NO;
            }else{
                jv.commitBtn.hidden = YES;
            }
            
        } failure:^(id  _Nonnull AJson) {
            
        }];
    }else{
        // 请登录
        AppDelegate *application = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [application needLoginVC:self];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self->joinBgView.hidden = YES;
    
//    if ([self.acitivityData[@"activityInfo"][@"activityState"] isEqualToString:@"1"]) {// 活动进行中
//        joinBtn.enabled = YES;
//        joinBtn.backgroundColor = [UIColor colorWithRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:1.0];
//        [joinBtn setTitle:@"参与报名" forState:UIControlStateNormal];
//    }else if([self.acitivityData[@"activityInfo"][@"activityState"] isEqualToString:@"3"]) {// 活动进行中
//        joinBtn.enabled = NO;
//        joinBtn.backgroundColor = [UIColor colorWithRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:1.0];
//        [joinBtn setTitle:@"报名成功，等待开奖" forState:UIControlStateNormal];
//    }else{
//        joinBtn.enabled = NO;
//        joinBtn.backgroundColor = [UIColor grayColor];
//        [joinBtn setTitle:@"已结束" forState:UIControlStateNormal];
//    }
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
////        NSLog(@"  x %f   y  %f ",scrollView.contentOffset.x,scrollView.contentOffset.y);
//    if (scrollView.contentOffset.y  >= 200) {
//        _collectionView.scrollEnabled = YES;
//    }else{
//        _collectionView.scrollEnabled = NO;
//    }
//}


#pragma mark - UICollectionView delegate & dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return labels.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((IPHONE_SCREEN_WIDTH - 15)/3, ((IPHONE_SCREEN_WIDTH - 15)/3)*1.5);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MBActivityCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MBActivityCollectionCell" forIndexPath:indexPath];
    //    NSArray *arr = self.worksD[@"worksList"];
    NSDictionary *dict = labels[indexPath.row];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:dict[@"coverUrl"]] placeholderImage:[UIImage imageNamed:@"bg.png"]];
    cell.userName.text = dict[@"nickname"];
    [cell.iconImg sd_setImageWithURL:[NSURL URLWithString:dict[@"headUrl"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"bg.png"]];
    [cell.likeLbl setTitle:filter(dict[@"transpond"]) forState:UIControlStateNormal];// 转发
    [cell.lookLbl setTitle:filter(dict[@"pageView"]) forState:UIControlStateNormal];// 观看
    if ([dict[@"type"] isEqualToString:@"1"]) {//短视频
        cell.flagImg.image = [UIImage imageNamed:@"duanship.png"];
    }else{//图片
        cell.flagImg.image = [UIImage imageNamed:@"pic.png"];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = labels[indexPath.row];
    if ([dict[@"type"] isEqualToString:@"1"]) {
        MBShortVideoPlayController *vc = [[MBShortVideoPlayController alloc]init];
        vc.videoPath = dict[@"videoUrl"];
        vc.videoID = filter(dict[@"videoId"]);
        vc.videoType = filter(dict[@"type2"]);
        vc.entityType = @"1";
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
        MBShortVideoPlayController *vc = [[MBShortVideoPlayController alloc]init];
        vc.videoPath = dict[@"videoUrl"];
        vc.videoID = filter(dict[@"videoId"]);
        vc.videoType = filter(dict[@"type2"]);
        vc.entityType = @"2";
        [self.navigationController pushViewController:vc animated:YES];
    }
}
@end
